package com.share.common.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.share.module.sys.user.entity.User;
import com.stock.common.constant.GlobalConstant;
import com.share.module.sys.user.service.UserService;
import com.stock.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (token == null) {
            throw new BusinessException(GlobalConstant.CODE_401, "无token，请重新登录");
        }

        String userId = JWT.decode(token).getAudience().get(0);
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(GlobalConstant.CODE_401, "用户不存在,请重新登录");
        }

        // 用户密码加签验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();

        try {
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            throw new BusinessException(GlobalConstant.CODE_401, "token验证失败，请重新登录");
        }

        return true;
    }
}
